<!-- from 7 5 2 7 1 8 9 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
                
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('reportQuery.searchType')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select :placeholder="$t('reportQuery.searchType')" allowClear v-model="queryParam.marginType">
                      <a-select-option :value="1">{{$t('reportQuery.customer')}}</a-select-option>
                      <a-select-option :value="2">{{$t('defaultTranslate.operator')}}</a-select-option>
                      <a-select-option :value="3">{{$t('reportQuery.commodity')}}</a-select-option>
                      </a-select>
                  </a-form-item>
                </a-col> 
                <a-col :md="6" :sm="24" v-if="queryParam.marginType == 1">
                  <a-form-item :label="$t('manuManagement.customer')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select :placeholder="$t('manuManagement.selectCustomer')" showSearch optionFilterProp="children" allowClear
                      v-model="queryParam.organId">
                      <a-select-option v-for="(item, index) in cusList" :key="index" :value="item.id">
                        {{ item.supplier }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                
                <a-col :md="6" :sm="24"  v-if="queryParam.marginType == 2">
                  <a-form-item :label="$t('defaultTranslate.operator')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select :placeholder="$t('defaultTranslate.operator')" allowClear v-model="queryParam.creator">
                      <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                      {{ item.userName }}
                        </a-select-option>
                      </a-select>
                  </a-form-item>
                </a-col>
                
              <a-col :md="6" :sm="24" v-if="queryParam.marginType == 3">
                <a-form-item :label="$t('reportQuery.goodsName')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :placeholder="$t('reportQuery.goodsName')" v-model="queryParam.materialName"  v-decorator="[ 'organId', validatorRules.materialName ]"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('reportQuery.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width: 100%"
                    v-model="queryParam.createTimeRange"
                    :default-value="defaultTimeStr"
                    format="YYYY-MM-DD"
                    :placeholder="[$t('reportQuery.startTime'), $t('reportQuery.endTime')]"
                    @change="onDateChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" >
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery">{{$t('reportQuery.query')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="reportPrint" icon="printer">{{$t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(3) > -1" :loading="downLoading" style="margin-left: 8px" @click="exportExcel" icon="download">{{$t('reportQuery.export')}}</a-button>
                 <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? $t('reportQuery.putAway'): $t('reportQuery.open') }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </span>
              </a-col>
              
              <template v-if="toggleSearchStatus">
                
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('commodityManagement.category')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-tree-select style="width:100%" :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                    :filterTreeNode="filterTreeNode"
                    showSearch
                      allow-clear :treeData="categoryTree" v-model="queryParam.categoryId"
                      :placeholder="$t('commodityManagement.pleaseCategory')">
                    </a-tree-select>
                  </a-form-item>
                </a-col>
              </template>
            </a-row>
            
            <template v-if="toggleSearchStatus">
                 
              </template>
          </a-form>
        </div>
        <!-- table区域-begin -->
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            :columns="columns"
            :customRow="rowClick"
            :dataSource="dataSource"
            :pagination="false"
            :loading="loading"
            @change="handleTableChange">
            <span slot="numberCustomRender" slot-scope="text, record">
              <a @click="myHandleDetail(record)">{{record.number}}</a>
            </span>
<!--             
            <span slot="action" slot-scope="text, record">
              <a @click="myHandleEdit(record)">{{$t('setailManagement.settlement')}}</a>
            </span> -->
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
            <a-col :md="24" :sm="24">
              <a-pagination @change="paginationChange" @showSizeChange="paginationShowSizeChange"
                size="small"
                show-size-changer
                :showQuickJumper="true"
                :current="ipagination.current"
                :page-size="ipagination.pageSize"
                :page-size-options="ipagination.pageSizeOptions"
                :total="ipagination.total"
                :show-total="(total, range) => $t('reportQuery.common') +`${total-Math.ceil(total/ipagination.pageSize)}`+ $t('reportQuery.strip')">
                <template slot="buildOptionText" slot-scope="props">
                  <span>{{ props.value-1 }}{{$t('reportQuery.strip')}}/{{$t('reportQuery.page')}}</span>
                </template>
              </a-pagination>
            </a-col>
          </a-row>
        </section>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <bill-detail ref="modalDetail"></bill-detail>
        <FinancialDetail ref="FinancialDetail"></FinancialDetail>
        <RebateReportModal ref="modalForm"></RebateReportModal>
      </a-card>
    </a-col>
    <saleOutRepotModual ref="saleOutRepotModual" :list="dataSource" :columns="columns" :queryParam="queryParam"></saleOutRepotModual>
  </a-row>
</template>
<script>
  import BillDetail from '@/views/bill/dialog/BillDetail'
  import FinancialDetail from '@/views/financial/dialog/FinancialDetail'
  import RebateReportModal from './modules/RebateReportModal';
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { BillListMixin } from '@/views/bill/mixins/BillListMixin'
  import { getNowFormatYear, openDownloadDialog, sheet2blob} from "@/utils/util"
  import {getAction} from '@/api/manage'
  import {findBySelectSup, findBillDetailByNumber,getUserList,findRebateDetail} from '@/api/api'
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import moment from 'moment'
  import saleOutRepotModual from './modules/saleOutRepotModual';
  export default {
    name: "SalesMarginDetailReport",
    mixins:[JeecgListMixin,BillListMixin],
    components: {
      BillDetail,
      FinancialDetail,
      JEllipsis,
      RebateReportModal,
      saleOutRepotModual
    },
    data () {
      return {
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        userList:[],
        subTypes:[],
        title:this.$t('otherJS.rebateReport'),
        // 查询条件
        queryParam: {
          organId: '',
          marginType:1,
          materialName:'',
          beginTime: getNowFormatYear() + '-01-01',
          endTime: moment().format('YYYY-MM-DD'),
          creator:'',
        },
        ipagination:{
          pageSize: 11,
          pageSizeOptions: ['11', '21', '31', '101', '201']
        },
        dateFormat: 'YYYY-MM-DD',
        currentDay: moment().format('YYYY-MM-DD'),
        defaultTimeStr: '',
        supList: [],
        depotList: [],
        tabKey: "1",
        // 表头
        columns: [
          {
            title: this.$t('defaultTranslate.lineNumber'), dataIndex: 'rowIndex', width:40, align:"center",
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {title:this.$t('setailManagement.documentNo'), dataIndex: 'number', width: 120, align:"center",ellipsis:true,
          scopedSlots: { customRender: 'numberCustomRender' },
          
          },
          {title:this.$t('manuManagement.customer'), dataIndex: 'supplier', width: 80,align:"center", ellipsis:true},
          {
            title: this.$t('reportQuery.goodsName'), dataIndex: 'materialName', width: 100,align:"center",
          },
          { title: this.$t('reportQuery.category'), dataIndex: 'categoryName',width:80 },
          {title:this.$t('reportQuery.color'), dataIndex: 'color', width: 80, ellipsis:true},
          {title:this.$t('reportQuery.salesCost'), dataIndex: 'salesCost',align:"center",  width: 60},
          {title:this.$t('reportQuery.grossMargin'), dataIndex: 'salesGrossMargin',align:"center", width: 60},
          {title:this.$t('reportQuery.salesMargin'), dataIndex: 'salesMargin', align:"center",width: 90},
          {title:this.$t('reportQuery.salesRevenue'), dataIndex: 'salesRevenue',align:"center", width: 60},
          {title:this.$t('defaultTranslate.operator'), dataIndex: 'loginName',align:"center", width: 80},
          { title: this.$t('manuManagement.documentDate'), dataIndex: 'operTime',align:"center", width: 100 },

          
        // {
        //   title: this.$t('manuManagement.operation'),
        //   dataIndex: 'action',
        //   align: "center", width: 70,
        //   scopedSlots: { customRender: 'action' },
        // }
          
        ],
        
        validatorRules:{
          operTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
        },
        url: {
          list: "/depotHead/findSalesMarginDetail",
        }
      }
    },
    created () {
    this.initUser()
    this.initCustomer()
      this.loadTreeData()
      this.defaultTimeStr = [moment(getNowFormatYear() + '-01-01', this.dateFormat), moment(this.currentDay, this.dateFormat)]
    },
    methods: {
      moment,
      getQueryParams() {
        this.queryParam.custom12 = this.queryParam.custom12 === undefined ? '' : this.queryParam.custom12
        this.queryParam.creator = this.queryParam.creator || '' 
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize-1;
        return param;
      },
      onDateChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.beginTime=dateString[0];
        this.queryParam.endTime=dateString[1];
      },
      initSupplier() {
        let that = this;
        findBySelectSup({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      getDepotData() {
        getAction('/depot/findDepotByCurrentUser').then((res)=>{
          if(res.code === 200){
            this.depotList = res.data;
          }else{
            this.$message.info(res.data);
          }
        })
      },
      myHandleDetail(record) {

        findBillDetailByNumber({ number: record.number }).then((res) => {
          if (res && res.code === 200) {
            let data = res.data
            this.handleDetail(res.data, data.subType + data.type);
          }
        })
      },
      myDetail(record){
        this.$refs.modalDetail.url.detailList = '/depotItem/findRebateDetail'
        this.$refs.modalDetail.title = '返利详情'
        this.$refs.modalDetail.show(record,'返利详情')
      },
      searchQuery() {
        if(this.queryParam.beginTime == '' || this.queryParam.endTime == ''){
          this.$message.warning(this.$t('reportQuery.pleaseDate'))
        } else {
          this.loadData(1);
        }
      },
      
    initUser () {
        getUserList({}).then((res) => {
          this.userList = res
        })
      },
      initSubTypes(){
        let arr = [this.$t('setailManagement.Unsettled') ,this.$t('setailManagement.Settled') ]
        this.subTypes = arr.map((val,idx)=>{
          let item= {
            label:val,
            value:idx
          }
          return item
        })
        console.log('this.subTypes :>> ', this.subTypes);
      },
      
    myHandleEdit (record) {
      if (record.custom12 === 0 || record.custom12 === 2) {
        this.$refs.modalForm.action = 'add'
        if (this.btnEnableList.indexOf(2) === -1) {
          this.$refs.modalForm.isCanCheck = false
        }
        this.handleEdit(record)
      } else {
        this.$message.warning('抱歉，只有未结算的单据才能编辑！')
      }
    },
    
    rowClick(record, index) {
      return {
        on: {
          click: () => {
          },
          dblclick: () => {
            // this.myHandleDetail(record, '预收款')
            // this.$refs.FinancialDetail.show(record,'返利详情')
            // this.myDetail(record)
          },
        }
      }
    },
      async exportExcel() {
        let aoa = [this.columns.map(v=>v.title)]
        this.downLoading = true
        // 获取要导出的数据
        let dataSource = await this.loadAllData(1)
        this.downLoading = false
        for (let i = 0; i < dataSource.length; i++) {
          let item = []
          for (let l = 0; l < this.columns.length; l++) {
            let column = this.columns[l]
              let text = dataSource[i][column.dataIndex] || ''
              // 有自定义方法
              if(typeof(column.customRender) ==="function"){
                let res = column.customRender(text,dataSource[i])
                // 返回的是node节点
                if(res && typeof(res.componentOptions)!="undefined"){
                  text = res.componentOptions.children[0].text
                }else{
                  text = res || ''
                }
              }
              item.push(text)
            
          }
          aoa.push(item)
        }
        openDownloadDialog(sheet2blob(aoa), this.title)
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>